package org.example.syn;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Yyming
 * Created by Yyming on 2021/4/23
 */
public class Dispatch {
    private static volatile int f = 0;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        ThreadA threadA = new ThreadA(lock, condition);
        ThreadB threadB = new ThreadB(lock, condition);
        threadB.start();
        threadA.start();


    }


    static class ThreadA extends Thread {
        ReentrantLock lock;
        Condition condition;

        public ThreadA(ReentrantLock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            try {
                lock.lock();
                while (true) {
                    try {
                        condition.signal();
                        System.out.print("A");
//                    countDownLatch.countDown();
                        condition.await();
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    static class ThreadB extends Thread {
        ReentrantLock lock;
        Condition condition;

        public ThreadB(ReentrantLock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            try {
                lock.lock();
                while (true) {
                    try {
                        condition.await();
                        System.out.print("B");
                        condition.signal();
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            } finally {
                lock.unlock();
            }


        }
    }


}
